package com.hongyu.smart.village.ui.activity;


import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;


import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import android.widget.Switch;


import com.hongyu.smart.village.R;
import com.hongyu.smart.village.event.Event;

import com.hongyu.smart.village.listener.OnItemClickListener;
import com.hongyu.smart.village.ui.adapter.BlueToothDeviceAdapter;
import com.hongyu.smart.village.ui.base.BaseActivity;
import com.hongyu.smart.village.util.bluetooth.BlueToothUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


public class BluetoothActivity extends BaseActivity {
    @BindView(R.id.sw_bluetooth)
    Switch aSwitch;
    @BindView(R.id.recycle_view_device)
    RecyclerView deviceRecycleView;
    @BindView(R.id.recycle_view_device_can_use)
    RecyclerView canUseRecycleView;
    BlueToothDeviceAdapter boundAdapter;
    BlueToothDeviceAdapter deviceAdapter;
    private List<String> boundStr=new ArrayList<>();
    private List<BluetoothDevice> boundDevices=new ArrayList<>();
    private List<String> deviceStr=new ArrayList<>();
    private BluetoothDevice bluetoothDevice;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initActivityData() {


    }

    @SuppressLint("MissingPermission")
    @Override
    protected void initContentView() {
        boundAdapter=new BlueToothDeviceAdapter(this,boundStr);
        boundAdapter.setmOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                bluetoothDevice=boundDevices.get(position);
                printTicket();


            }
        });
        deviceRecycleView.setLayoutManager(new LinearLayoutManager(this));
        deviceRecycleView.setAdapter(boundAdapter);
        permission_request();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);



    }

    private void printTicket() {
        PrtinterThread thread=new PrtinterThread();
        thread.start();

    }

    @SuppressLint("MissingPermission")
    @OnClick({R.id.tv_scan})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_scan:
                getBoundDevice();
                startDiscovery();


                break;
        }
    }

    @SuppressLint("MissingPermission")
    private void getBoundDevice() {
        Set<BluetoothDevice> pairedDevices = BlueToothUtils.getInstance().getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                boundStr.add(device.getName()+"\n"+device.getAddress());
                Log.i(device.getName(),device.getAddress());
                boundDevices.add(device);
            }
        }
        boundAdapter.notifyDataSetChanged();
    }

    private void startDiscovery() {
        BlueToothUtils.getInstance().startDiscovery();
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_bluetooth;
    }

    @Override
    protected void onEventProcess(Event event) {

    }
    private void permission_request(){
        ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.BLUETOOTH}, 1);
    }


    @SuppressLint("MissingPermission")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode==1){
            for (int i=0;i<grantResults.length;i++){
                if (grantResults[i]!=0){   //权限成功
                    System.exit(0);
                }
            }
            Intent intentw = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            //设置可被发现的时间，00s
            intentw.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(intentw);
            if(BlueToothUtils.getInstance().supportBlueTooth()){
                BlueToothUtils.getInstance().openBluetooth(BluetoothActivity.this);
            }
        }
        if (requestCode==2){
            for (int i=0;i<grantResults.length;i++){
                if (grantResults[i]!=0){   //权限成功

                }
            }
        }
    }
    public  final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // 当有设备被发现的时候会收到 action == BluetoothDevice.ACTION_FOUND 的广播
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {

                //广播的 intent 里包含了一个 BluetoothDevice 对象
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                //假设我们用一个 ListView 展示发现的设备，那么每收到一个广播，就添加一个设备到 adapter 里
                Log.i(device.getName() , device.getAddress());
            }
        }
    };
    private class PrtinterThread extends Thread{
        @Override
        public void run() {
            super.run();
            printService.connectPrinter(bluetoothDevice);
            printService.printTicket();
        }
    }

}